<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="jquery-ui/css/smoothness/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-ui/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="i18n.js" charset="utf-8"></script>
<title>Adblock Plus Options</title>
<style type="text/css" media="screen">
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
    padding: 20px;
}

td {
    font-size: 13px;
    vertical-align: top;
    text-align: left;
}

p {
    margin-top: 0.5em;
}

#subscriptionTemplate,
#addSubscriptionContainer,
#customSubscriptionContainer
{
  display: none;
}

.subscription
{
  margin: 3px 0px;
}

.subscriptionRemoveButton,
.subscriptionEnabledContainer,
.subscriptionTitle
{
  margin-right: 1em;
}

.subscriptionRemoveButton
{
  font-weight: normal !important;
  font-size: 20px !important;
  color: #FF0000 !important;
  border: none !important;
  outline: none !important;
  background: none !important;
}

.subscriptionUpdate
{
  color: #B0B0B0;
}
.subscriptionUpdate.error
{
  color: #FF0000;
}

#rawFilters {
  display: none;
}

.okMsg {
    display: none;
    color: #ffffff;
    background: #30e030;
    font-weight: bold;
    padding: 3px;
}

.errMsg {
    display: none;
    color: #ffffff;
    background: #e03030;
    font-weight:bold;
    padding:3px;
}

/* Filter list entry status message */
.flMsg {
    display: none;
    color: #b0b0b0;
}

</style>
<script type="text/javascript" charset="utf-8">

var backgroundPage = chrome.extension.getBackgroundPage();
var imports = ["FilterStorage", "FilterNotifier", "Subscription", "SpecialSubscription",
               "DownloadableSubscription", "Filter", "WhitelistFilter",
               "Synchronizer", "Utils", "hasExperimentalPermissions"];
for (var i = 0; i < imports.length; i++)
  window[imports[i]] = backgroundPage[imports[i]];

// Loads options from localStorage and sets UI elements accordingly
function loadOptions()
{
  FilterNotifier.addListener(onFilterChange);

  // Popuplate option checkboxes
  initCheckbox("shouldShowIcon");
  initCheckbox("shouldShowBlockElementMenu");
  initCheckbox("disableInlineTextAds");
  initCheckbox("specialCaseYouTube");
  initCheckbox("hidePlaceholders");

  if (hasExperimentalPermissions)
    document.getElementById("specialCaseYouTubeContainer").style.display = "none";
  else
    document.getElementById("hidePlaceholdersContainer").style.display = "none";

  // Load recommended subscriptions
  loadRecommendations();

  // Show user's filters
  reloadFilters();
}

// Reloads the displayed subscriptions and filters
function reloadFilters()
{
  // Load user filter URLs
  var container = document.getElementById("filterLists");
  while (container.lastChild)
    container.removeChild(container.lastChild);

  for (var i = 0; i < FilterStorage.subscriptions.length; i++)
  {
    var subscription = FilterStorage.subscriptions[i];
    if (subscription instanceof SpecialSubscription)
      continue;

    addSubscriptionEntry(subscription);
  }

  // User-entered filters
  showUserFilters();
}

// Cleans up when the options window is closed
function unloadOptions()
{
  FilterNotifier.removeListener(onFilterChange);
}

function initCheckbox(id)
{
  var checkbox = document.getElementById(id);
  checkbox.checked = typeof localStorage[id] == "undefined" ? true : localStorage[id] == "true";
  checkbox.addEventListener("click", function()
  {
    localStorage[id] = checkbox.checked;
  }, false);
}

function showUserFilters()
{
  var filters = [];
  var exceptions = [];
  for (var i = 0; i < FilterStorage.subscriptions.length; i++)
  {
    var subscription = FilterStorage.subscriptions[i];
    if (!(subscription instanceof SpecialSubscription))
      continue;

    for (var j = 0; j < subscription.filters.length; j++)
    {
      var filter = subscription.filters[j];
      if (filter instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(filter.text))
        exceptions.push(RegExp.$1)
      else
        filters.push(filter.text);
    }
  }

  populateList("userFiltersBox", filters);
  populateList("excludedDomainsBox", exceptions);
}

var delayedSubscriptionSelection = null;

function loadRecommendations()
{
  var request = new XMLHttpRequest();
  request.open("GET", "subscriptions.xml");
  request.onload = function()
  {
    var selectedIndex = 0;
    var selectedPrefix = null;
    var matchCount = 0;

    var list = document.getElementById("subscriptionSelector");
    var elements = request.responseXML.documentElement.getElementsByTagName("subscription");
    for (var i = 0; i < elements.length; i++)
    {
      var element = elements[i];
      var option = document.createElement("option");
      option.text = element.getAttribute("title") + " (" + element.getAttribute("specialization") + ")";
      option._data = {
        title: element.getAttribute("title"),
        url: element.getAttribute("url"),
        homepage: element.getAttribute("homepage")
      };

      var prefix = Utils.checkLocalePrefixMatch(element.getAttribute("prefixes"));
      if (prefix)
      {
        option.style.fontWeight = "bold";
        option.style.backgroundColor = "#E0FFE0";
        option.style.color = "#000000";
        if (!selectedPrefix || selectedPrefix.length < prefix.length)
        {
          selectedIndex = i;
          selectedPrefix = prefix;
          matchCount = 1;
        }
        else if (selectedPrefix && selectedPrefix.length == prefix.length)
        {
          matchCount++;

          // If multiple items have a matching prefix of the same length:
          // Select one of the items randomly, probability should be the same
          // for all items. So we replace the previous match here with
          // probability 1/N (N being the number of matches).
          if (Math.random() * matchCount < 1)
          {
            selectedIndex = i;
            selectedPrefix = prefix;
          }
        }
      }
      list.appendChild(option);
    }

    var option = document.createElement("option");
    option.text = chrome.i18n.getMessage("filters_addSubscriptionOther_label") + "\u2026";
    option._data = null;
    list.appendChild(option);

    list.selectedIndex = selectedIndex;

    if (delayedSubscriptionSelection)
      startSubscriptionSelection.apply(null, delayedSubscriptionSelection);
  };
  request.send(null);
}

function startSubscriptionSelection(title, url)
{
  var list = document.getElementById("subscriptionSelector");
  if (list.length == 0)
  {
    delayedSubscriptionSelection = [title, url];
    return;
  }

  $('#tabs').tabs('select', 0);
  $("#addSubscriptionContainer").show();
  $("#addSubscriptionButton").hide();
  $("#subscriptionSelector").focus();
  if (typeof url != "undefined")
  {
    list.selectedIndex = list.length - 1;
    document.getElementById("customSubscriptionTitle").value = title;
    document.getElementById("customSubscriptionLocation").value = url;
  }
  updateSubscriptionSelection();
  document.getElementById("addSubscriptionContainer").scrollIntoView(true);
}

function updateSubscriptionSelection()
{
  var list = document.getElementById("subscriptionSelector");
  var data = list.options[list.selectedIndex]._data;
  if (data)
    $("#customSubscriptionContainer").hide();
  else
  {
    $("#customSubscriptionContainer").show();
    $("#customSubscriptionTitle").focus();
  }
}

function addSubscription()
{
  var list = document.getElementById("subscriptionSelector");
  var data = list.options[list.selectedIndex]._data;
  if (data)
    doAddSubscription(data.url, data.title, data.homepage);
  else
  {
    var url = document.getElementById("customSubscriptionLocation").value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (!/^https?:/i.test(url))
    {
      alert(chrome.i18n.getMessage("global_subscription_invalid_location"));
      $("#customSubscriptionLocation").focus();
      return;
    }

    var title = document.getElementById("customSubscriptionTitle").value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (!title)
      title = url;

    doAddSubscription(url, title, null);
  }

  $("#addSubscriptionContainer").hide();
  $("#customSubscriptionContainer").hide();
  $("#addSubscriptionButton").show();
}

function doAddSubscription(url, title, homepage)
{
  if (url in FilterStorage.knownSubscriptions)
    return;

  var subscription = Subscription.fromURL(url);
  if (!subscription)
    return;

  subscription.title = title;
  if (homepage)
    subscription.homepage = homepage;
  FilterStorage.addSubscription(subscription);

  if (subscription instanceof DownloadableSubscription && !subscription.lastDownload)
    Synchronizer.execute(subscription);
}

function findSubscriptionElement(subscription)
{
  var children = document.getElementById("filterLists").childNodes;
  for (var i = 0; i < children.length; i++)
    if (children[i]._subscription == subscription)
      return children[i];
  return null;
}

function updateSubscriptionInfo(element)
{
  var subscription = element._subscription;

  var title = element.getElementsByClassName("subscriptionTitle")[0];
  title.textContent = subscription.title;
  title.setAttribute("title", subscription.url);
  if (subscription.homepage)
    title.href = subscription.homepage;
  else
    title.href = subscription.url;

  var enabled = element.getElementsByClassName("subscriptionEnabled")[0];
  enabled.checked = !subscription.disabled;

  var lastUpdate = element.getElementsByClassName("subscriptionUpdate")[0];
  lastUpdate.classList.remove("error");
  if (Synchronizer.isExecuting(subscription.url))
    lastUpdate.textContent = chrome.i18n.getMessage("filters_subscription_lastDownload_inProgress");
  else if (subscription.downloadStatus && subscription.downloadStatus != "synchronize_ok")
  {
    var map =
    {
      "synchronize_invalid_url": "filters_subscription_lastDownload_invalidURL",
      "synchronize_connection_error": "filters_subscription_lastDownload_connectionError",
      "synchronize_invalid_data": "filters_subscription_lastDownload_invalidData",
      "synchronize_checksum_mismatch": "filters_subscription_lastDownload_checksumMismatch"
    };
    if (subscription.downloadStatus in map)
      lastUpdate.textContent = chrome.i18n.getMessage(map[subscription.downloadStatus]);
    else
      lastUpdate.textContent = subscription.downloadStatus;
    lastUpdate.classList.add("error");
  }
  else if (subscription.lastDownload > 0)
  {
    var timeDate = i18n_timeDateStrings(subscription.lastDownload * 1000);
    var messageID = (timeDate[1] ? "last_updated_at" : "last_updated_at_today");
    lastUpdate.textContent = chrome.i18n.getMessage(messageID, timeDate);
  }
}

function onFilterChange(action, item, param1, param2)
{
  switch (action)
  {
    case "load":
      reloadFilters();
      break;
    case "subscription.title":
    case "subscription.disabled":
    case "subscription.homepage":
    case "subscription.lastDownload":
    case "subscription.downloadStatus":
      var element = findSubscriptionElement(item);
      if (element)
        updateSubscriptionInfo(element);
      break;
    case "subscription.added":
      if (!(item instanceof SpecialSubscription) && !findSubscriptionElement(item))
        addSubscriptionEntry(item);
      break;
    case "subscription.removed":
      var element = findSubscriptionElement(item);
      if (element)
        element.parentNode.removeChild(element);
      break;
    case "filter.added":
      if (item instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(item.text))
        appendToListBox("excludedDomainsBox", RegExp.$1);
      else
        appendToListBox("userFiltersBox", item.text);
      break;
    case "filter.removed":
      if (item instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(item.text))
        removeFromListBox("excludedDomainsBox", RegExp.$1);
      else
        removeFromListBox("userFiltersBox", item.text);
      break;
  }
}

// Populates a list box with a number of entries
function populateList(id, entries)
{
  var list = document.getElementById(id);
  while (list.lastChild)
    list.removeChild(list.lastChild);

  entries.sort();
  for (var i = 0; i < entries.length; i++)
  {
    var option = document.createElement("option");
    option.text = entries[i];
    option.value = entries[i];
    list.appendChild(option);
  }
}

// Add a filter string to the list box.
function appendToListBox(boxId, text)
{
  var elt = document.createElement("option");
  elt.text = text;
  elt.value = text;
  document.getElementById(boxId).appendChild(elt);
}

// Remove a filter string from a list box.
function removeFromListBox(boxId, text)
{
  var elt = document.createElement("option");
  elt.text = text;
  elt.value = text;
  var list = document.getElementById(boxId);
  for (var i = 0; i < list.length; i++)
    if (list.options[i].value == text)
      list.remove(i--);
}

function addWhitelistDomain()
{
  var domain = document.getElementById("newWhitelistDomain").value.replace(/\s/g, "");
  document.getElementById("newWhitelistDomain").value = "";
  if (!domain)
    return;

  var filterText = "@@||" + domain + "^$document";
  FilterStorage.addFilter(Filter.fromText(filterText));
}

// Adds filter text that user typed to the selection box
function addTypedFilter()
{
  var filterText = Filter.normalize(document.getElementById("newFilter").value);
  document.getElementById("newFilter").value = "";
  if (!filterText)
    return;

  FilterStorage.addFilter(Filter.fromText(filterText));
}

// Removes currently selected whitelisted domains
function removeSelectedExcludedDomain()
{
  var excludedDomainsBox = document.getElementById("excludedDomainsBox");
  var remove = [];
  for (var i = 0; i < excludedDomainsBox.length; i++)
    if (excludedDomainsBox.options[i].selected)
      remove.push(excludedDomainsBox.options[i].value);
  if (!remove.length)
    return;

  for (var i = 0; i < remove.length; i++)
    FilterStorage.removeFilter(Filter.fromText("@@||" + remove[i] + "^$document"));
}

// Removes all currently selected filters
function removeSelectedFilters()
{
  var userFiltersBox = document.getElementById("userFiltersBox");
  var remove = [];
  for (var i = 0; i < userFiltersBox.length; i++)
    if (userFiltersBox.options[i].selected)
      remove.push(userFiltersBox.options[i].value);
  if (!remove.length)
    return;

  for (var i = 0; i < remove.length; i++)
    FilterStorage.removeFilter(Filter.fromText(remove[i]));
}

// Shows raw filters box and fills it with the current user filters
function toggleFiltersInRawFormat()
{
  $("#rawFilters").toggle();
  if ($("#rawFilters").is(":visible"))
  {
    var userFiltersBox = document.getElementById("userFiltersBox");
    var text = "";
    for (var i = 0; i < userFiltersBox.length; i++)
      text += userFiltersBox.options[i].value + "\n";
    document.getElementById("rawFiltersText").value = text;
  }
}

// Imports filters in the raw text box
function importRawFiltersText()
{
  $("#rawFilters").hide();
  var filters = document.getElementById("rawFiltersText").value.split("\n");
  var seenFilter = {__proto__: null};
  for (var i = 0; i < filters.length; i++)
  {
    var text = Filter.normalize(filters[i]);
    if (!text)
      continue;

    // Don't import filter list header
    if (/^\[/.test(text))
      continue;

    FilterStorage.addFilter(Filter.fromText(text));
    seenFilter[text] = true;
  }

  var remove = [];
  for (var i = 0; i < FilterStorage.subscriptions.length; i++)
  {
    var subscription = FilterStorage.subscriptions[i];
    if (!(subscription instanceof SpecialSubscription))
      continue;

    for (var j = 0; j < subscription.filters.length; j++)
    {
      var filter = subscription.filters[j];
      if (filter instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(filter.text))
        continue;

      if (!(filter.text in seenFilter))
        remove.push(filter);
    }
  }
  for (var i = 0; i < remove.length; i++)
    FilterStorage.removeFilter(remove[i]);
}

// Called when user explicitly requests filter list updates
function updateFilterLists()
{
  for (var i = 0; i < FilterStorage.subscriptions.length; i++)
  {
    var subscription = FilterStorage.subscriptions[i];
    if (subscription instanceof DownloadableSubscription)
      Synchronizer.execute(subscription, true, true);
  }
}

// Adds a subscription entry to the UI.
function addSubscriptionEntry(subscription)
{
  var template = document.getElementById("subscriptionTemplate");
  var element = template.cloneNode(true);
  element.removeAttribute("id");
  element._subscription = subscription;

  var removeButton = element.getElementsByClassName("subscriptionRemoveButton")[0];
  removeButton.setAttribute("title", removeButton.textContent);
  removeButton.textContent = "\xD7";
  removeButton.addEventListener("click", function()
  {
    if (!confirm(chrome.i18n.getMessage("global_remove_subscription_warning")))
      return;

    FilterStorage.removeSubscription(subscription);
  }, false);

  var enabled = element.getElementsByClassName("subscriptionEnabled")[0];
  enabled.addEventListener("click", function()
  {
    if (subscription.disabled == !enabled.checked)
      return;

    subscription.disabled = !enabled.checked;
  }, false);

  updateSubscriptionInfo(element);

  document.getElementById("filterLists").appendChild(element);
}

// Set page title to i18n version of "Adblock Plus Options"
document.title = chrome.i18n.getMessage("options");

// Display jQuery UI elements
$(function() { 
    $('#tabs').tabs(); 
    $('button').button(); 
    $('.refreshButton').button('option', 'icons', {primary: 'ui-icon-refresh'});
    $('.addButton').button('option', 'icons', {primary: 'ui-icon-plus'});
    $('.removeButton').button('option', 'icons', {primary: 'ui-icon-minus'});
});


</script>
</head>
<body onload="loadI18nStrings(); loadOptions();" onunload="unloadOptions();">
<table>
  <tr>
    <td style="padding-right: 8px">
      <img src="icons/abp-32.png">
    </td>
    <td>
      <h1><span class="i18n_options"></span></h1>
    </td>
  </tr>
</table>

<div id="tabs">
  <ul>
    <li><a href="#tab-filterlists"><span class="i18n_filter_lists"></span></a></li>
    <li><a href="#tab-userfilters"><span class="i18n_add_your_own_filters"></span></a></li>
    <li><a href="#tab-whitelisted"><span class="i18n_whitelisted_domains"></span></a></li>
    <li><a href="#tab-general"><span class="i18n_general"></span></a></li>
  </ul>

  <div id="tab-filterlists">
    <p>
      <span class="i18n_enable_only_the"></span>
    </p>
    <p>
      <span class="i18n_out_of_date_lists"></span>
      <button class="refreshButton" onclick="updateFilterLists()"><span class="i18n_update_now"></span></button><br />

      <!-- Subscription entry template -->
      <div id="subscriptionTemplate" class="subscription">
        <button class="i18n_filters_subscription_delete_label subscriptionRemoveButton"></button>
        <span class="subscriptionEnabledContainer">
          <input class="subscriptionEnabled" type="checkbox" /> <span class="i18n_filters_subscription_enabled_label"></span>
        </span>
        <a class="subscriptionTitle"></a>
        <span class="subscriptionUpdate"></span>
      </div>

      <!-- Placeholder for list of subscriptions -->
      <div id="filterLists"></div>
      <br />

      <!-- Placeholder for user's filter list URLs -->
      <div id="userFilterLists" style="margin-bottom: 8px"></div>

      <p id="addSubscriptionButton">
        <button class="addButton" onclick="startSubscriptionSelection();"><span class="i18n_filters_addSubscription_label"></span></button>
      </p>
      <div id="addSubscriptionContainer">
        <span class="i18n_subscriptionSelection_subscriptionSelector_label"></span><br />
        <select id="subscriptionSelector" onchange="updateSubscriptionSelection();" style="width:500px"></select>
        <button class="addButton" onclick="addSubscription()"><span class="i18n_filters_addSubscriptionAdd_label"></span></button>
      </div>
      <div id="customSubscriptionContainer">
        <p>
          <span class="i18n_subscriptionSelection_title_label"></span><br />
          <input type="text" id="customSubscriptionTitle" style="width:500px" />
        </p>
        <p>
          <span class="i18n_subscriptionSelection_location_label"></span><br />
          <input type="text" id="customSubscriptionLocation" style="width:500px" />
        </p>
      </div>
    </p>
  </div>

  <div id="tab-whitelisted">
    <p class="i18n_disabled_for_these_domains"></p>

    <form action="#" onsubmit="addWhitelistDomain();return false;">
    <table>
      <tr>
        <td style="max-width:100%">
          <input type="text" value="" id="newWhitelistDomain" style="width:100%">
        </td>
        <td>
          <button class="addButton" type="submit"><span class="i18n_add_domain_button"></span></button>
        </td>
      </tr>

      <tr>
        <td>
          <select id="excludedDomainsBox" size="10" multiple style="width:500px; background: white;"></select>
        </td>
        <td>
          <button class="removeButton" onclick="removeSelectedExcludedDomain()"><span class="i18n_remove_button"></span></button>
        </td>
      </tr>
    </table>
    </form>
  </div>

  <div id="tab-userfilters">
    <p class="i18n_filter_must_follow_syntax">"http://adblockplus.org/en/filters"</p>

    <form action="#" onsubmit="addTypedFilter();return false;">
    <table>
      <tr>
        <td>
          <input type="text" value="" id="newFilter" style="width:500px">
        </td>
        <td>
          <button class="addButton" type="submit"><span class="i18n_add_filter_button"></span></button>
        </td>
      </tr>
      <tr>
        <td>
          <select id="userFiltersBox" size="20" multiple style="width: 500px; background: white;"></select>
        </td>
        <td>
          <button class="removeButton" onclick="removeSelectedFilters()"><span class="i18n_remove_button"></span></button>
        </td>
      </tr>
      <tr>
        <td>
          <div style="font-size: 90%; text-align: right"><a onclick="toggleFiltersInRawFormat()" href="#"><span class="i18n_edit_filters_raw"></span></a></div>
        </td>
      </tr>
      <tr id="rawFilters">
        <td>
          <div style="width: 500px">
            <textarea id="rawFiltersText" style="width: 100%; height: 300px"></textarea>
          </div>
        </td>
        <td>
          <div><button onclick="importRawFiltersText()"><span class="i18n_apply_changes"></span></button></div>
        </td>
      </tr>
    </table>
    </form>
  </div>

  <div id="tab-general">
    <p>
      <div id="shouldShowIconContainer">
        <input type="checkbox" id="shouldShowIcon" /><span class="i18n_show_icon"></span>
      </div>
      <div id="shouldShowBlockElementMenuContainer">
        <input type="checkbox" id="shouldShowBlockElementMenu" /><span class="i18n_show_block_element_menu"></span>
      </div>
      <div id="disableInlineTextAdsContainer">
        <input type="checkbox" id="disableInlineTextAds" /><span class="i18n_disable_inline"></span>
      </div>
      <div id="specialCaseYouTubeContainer">
        <input type="checkbox" id="specialCaseYouTube" /><span class="i18n_block_youtube"></span>
      </div>
      <div id="hidePlaceholdersContainer">
        <input type="checkbox" id="hidePlaceholders" /><span class="i18n_overlay_hideplaceholders_label"></span>
      </div>
    </p>

    <p class="i18n_found_a_bug">"https://adblockplus.org/forum/viewforum.php?f=10"</p>
  </div>
</div>

</body>
</html>
